<template>
  <div class="department-container">

    <el-tree :data="data" empty-text="当前组织架构数据为空..." default-expand-all :expand-on-click-node="false">
      <div slot-scope="{data: data1}" class="item">
        <div class="left">{{ data1.name }}</div>
        <div class="right">
          <span class="ir-name">{{ data1.managerName }}</span>
          <el-dropdown @command="handleCommand($event, data1.id)">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="add">添加子部门</el-dropdown-item>
              <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
              <el-dropdown-item command="del">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </el-tree>

    <addDeptVue ref="addDeptRef" :visible.sync="dialogVisible" :origin-list="originList" :current-id="currentId" @updateParent="getDepartment" />

  </div>
</template>

<script>
import { getDepartmentRequest, deleteDepartmentByIdRequest } from '@/api/department'
import { transfromListToTree } from '@/utils'
import addDeptVue from './add-dept.vue'

export default {
  name: 'DepartmentCom',
  components: { addDeptVue },
  data() {
    return {
      data: [],
      count: 1,
      msg: 10,
      dialogVisible: false,
      originList: [],
      currentId: null
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    fn(a, b) {
      console.log(a, b)
    },
    handleCommand(command, id) {
      console.log(command, id)
      this.currentId = id
      if (command === 'add') {
        this.dialogVisible = true
      } else if (command === 'edit') {
        console.log(1)
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.addDeptRef.getDepartmentById()
        })
        console.log(2)
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await deleteDepartmentByIdRequest(id)
          this.getDepartment()
          this.$message.success('删除部门成功')
        }).catch(() => {
        })
      }
    },
    async getDepartment() {
      const res = await getDepartmentRequest()
      this.originList = res.data
      this.data = transfromListToTree(res.data, 0)
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 20px;
}
.item {
  width: 100%;
  display: flex;
  .left {
    flex: 4;
    padding: 10px 0;
  }
  .right {
    flex: 1;
    padding: 10px 0;
    .ir-name {
      margin-right: 15px;
    }
  }
}

.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
